#-*- coding:UTF-8-*-

__author__='zhaoxp'

import contextlib

def foo():
    print 'before foo()'
    yield 'foo()'
    print 'in foo()'
    yield 'foo() 2'
    print 'after foo()'

@contextlib.contextmanager
def demo():
    print('[allocate resources]')
    print('code before yield-statement executes in __enter__')
    yield '*** contextmanager demo ***'
    print('code after yield-statement executes in __exit__')
    print('[free resource]')

class closing(object):
    def __init__(self,thing):
        self.thing=thing
    def __enter__(self):
        return self.thing
    def __exit__(self,*exec_info):
        self.thing.close()

class ClosingDemo(object):
    def __init__(self):
        self.acquire()
    def acquire(self):
        print('Acquire resources')
    def free(self):
        print('Clean up any resources acquired')
    def close(self):
        self.free()

if __name__=='__main__':
    print('*'*40)
    print('foo()')
    f=foo()
    print f
    try:
        while True:
            print('--next()'+str(f.next()))
    except StopIteration,s:
        print('end of iteration'+str(s))
    print('*'*40)
    with demo() as value:
        print 'assigned value: %s'%value
    print('*'*40)
    print('normal with')
    with open(r'contextlib_usage.py','r') as fin1:
        with open(r'argparse_usage.py','r') as fin2:
            with open(r'temp.txt','w') as fout:
                for l1 in fin1:
                    fout.write(l1)
                for l2 in fin2:
                    fout.write(l2)
    print(fin1,fin2,fout)
    print('*'*40)
    print('with by contextlib.nested')
    with contextlib.nested(open(r'contextlib_usage.py','r'),open(r'argparse_usage.py','r'),open(r'temp2.txt','w')) as (fin1,fin2,fout):
        for l1 in fin1:
            fout.write(l1)
        for l2 in fin2:
            fout.write(l2)
    print(fin1,fin2,fout)
    print('*'*40)
    print("show closing example:")
    with closing(ClosingDemo()):
        print("Using resources")
    print('*'*40)
    

